<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 16/4/5
 * Time: 上午11:12
 * Describe:
 */

namespace wap\controllers;


use liketry\models\OrderMemberMoneySmsForm;
use services\models\Cart;
use services\models\discount\FullCut;
use services\models\MemberInfo;
use services\models\Order;
use services\models\OrderDiscount;
use services\models\OrderInfo;
use Yii;
use services\models\Product;
use services\models\GoodsDetail;
use services\models\ProductDetail;
use services\models\Goods;
use services\models\MemberAddress;
use services\models\Payment;
use yii\base\Exception;
use yii\web\NotFoundHttpException;

class OrderController extends CustomController
{
    public function cartIdsProc($cart_ids)
    {
        return array_filter(explode(',', $cart_ids), function ($v) {
            if (!$v || !preg_match('/^\d+$/', $v)) {
                return false;
            }
            return true;
        });
    }

    public function beforeAction($action)
    {

        $result = parent::beforeAction($action);
        if (empty($this->bestry_uid)) {
            $this->redirect($this->login_url);
            return false;
        }
        return $result;

    }

    public function actions()
    {
        return [
            'error'  => [
                'class' => 'yii\web\ErrorAction',
            ],
            'alipay' => [
                'class' => 'components\WapAlipayAction',
            ],

        ];
    }

    public function actionIndex()
    {

        $cart_ids = Yii::$app->request->get('cart_ids', '');
        $uid      = Yii::$app->request->get('uid');                 //地址id


        //请求默认地址
        $MemberAddress = new MemberAddress();
        $memberInfo    = $MemberAddress->getMemberAddressInfo($this->bestry_uid, $uid);

        $order           = new Order();
        $order->cart_ids = $this->cartIdsProc($cart_ids);

        $order->bestry_uid        = $this->bestry_uid;
        $order->member_address_id = empty($memberInfo) ? null : $memberInfo->uid;

        $order->validate();
        OrderDiscount::discount($order);
        $order->format();
        $gdms = $order->getDiscountMsg();
        $gdm  = array_filter(
            $gdms, function ($item) {
            /** @var \common\models\OrderDiscount $item */
            if ($item->type == \services\models\discount\FullCut::shortClassName()) {
                return true;
            }
            return false;
        });
        if (!empty($gdm)) {
            $gdm     = array_pop($gdm);
            $fullcut = $gdm->describe;
        } else {
            $fc            = new FullCut();
            $discount_data = $fc->getDataFromRedis();
            if (empty($discount_data)) {
                $fullcut = '';
            } else {
                $fullcut = $discount_data['desc'];
            }

        }

        if (isset($memberInfo['code']))
            $memberInfo = '';
        return $this->render('@wap/views/cart/order', [
            'order'        => $order,
            'cellConfirm'  => $order->memberInfoBestry->memberInfo->cellConfirm(),
            'memberBty'    => $order->memberInfoBestry,
            'fullcut'      => $fullcut,
            'member_money' => $order->memberInfoBestry->member_money,
            'memberInfo'   => $memberInfo,
            'cart_ids'     => $cart_ids,
        ]);
    }

    /**
     * try_coin 支付快递费 , 判断try_coin是否充足
     * @return array
     */
    public function actionValidate()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $order                           = new Order();
        $order->cart_ids                 = $this->cartIdsProc(Yii::$app->request->post('cart_ids', ''));
        $order->bestry_uid               = $this->bestry_uid;
        $order->member_address_id        = intval(Yii::$app->request->post('member_address_id', 0));
        $order->use_coin_for_ship_amount = intval(Yii::$app->request->post('use_coin_for_ship_amount', 0));
        $order->member_money             = floatval(Yii::$app->request->post('member_money', 0));
        $order->sms_confirm_code         = Yii::$app->request->post('smsConfirm', 0);

        $order->validate();
        OrderDiscount::discount($order);
        $order->format();

        return ['flag'                 => $order->hasErrors() ? false : true, 'msg' => $order->getErrors(),
                'try_coin'             => $order->try_coin,
                'ship_amount_try_coin' => $order->ship_amount_try_coin,
                'order_amount'         => $order->order_amount,
                'ship_amount'          => $order->ship_amount,
                'ship_amount_discount' => $order->ship_amount_discount,
        ];

    }


    /**
     * 使用余额, 发送短信验证
     *
     * @return array
     */
    public function actionMemberMoneySms()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $model = new OrderMemberMoneySmsForm();

        $money               = floatval(Yii::$app->request->post('member_money', 0));
        $model->member_money = $money;
        $model->bestry_uid   = $this->bestry_uid;

        $model->validate();


        if ($model->hasErrors()) {
            return ['flag' => false, 'errCode' => $model->getErrors()];
        }

        if ($model->sendSms()) {
            return ['flag' => true, 'errCode' => null];
        } else {
            return ['flag' => false, 'errCode' => $model->getErrors()];
        }

    }


    /**
     * 验证用户输入短信码是否正确
     *
     * @return array|bool
     */
    public function actionMemberMoneySmsCheck()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $smsConfirm                 = Yii::$app->request->post('smsConfirm', '');
        if (!$smsConfirm) {
            return ['flag' => false, 'msg' => '验证码不能为空'];
        }
        $cell = MemberInfo::cache($this->liketry_uid)->cell;
        $code = MemberInfo::getCellCode($cell);
        if (!empty($smsConfirm) && $smsConfirm != $code) {
            return ['flag' => false, 'msg' => '验证码不正确'];
        }
        $order                           = new Order();
        $order->cart_ids                 = $this->cartIdsProc(Yii::$app->request->post('cart_ids', ''));
        $order->bestry_uid               = $this->bestry_uid;
        $order->member_address_id        = intval(Yii::$app->request->post('member_address_id', 0));
        $order->use_coin_for_ship_amount = intval(Yii::$app->request->post('use_coin_for_ship_amount', 0));
        $order->member_money             = floatval(Yii::$app->request->post('member_money', 0));
        $order->sms_confirm_code         = $smsConfirm;

        $order->validate();
        OrderDiscount::discount($order);
        $order->format();

        return ['flag'                 => $order->order_amount < 0 ? false : true,
                'msg'                  => $order->order_amount < 0 ? '余额不能超过订单金额' : '',
                'try_coin'             => $order->try_coin,
                'ship_amount_try_coin' => $order->ship_amount_try_coin,
                'order_amount'         => $order->order_amount,
                'ship_amount'          => $order->ship_amount,
                'ship_amount_discount' => $order->ship_amount_discount,
                'reduce_amount'        => $order->reduce_amount,
        ];

    }


    /**
     * 保存订单
     * @return array
     */
    public function actionSave()
    {

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $cart_ids = $this->cartIdsProc(Yii::$app->request->post('cart_ids', ''));

        $member_address_id        = intval(Yii::$app->request->post('member_address_id', 0));
        $use_coin_for_ship_amount = intval(Yii::$app->request->post('use_coin_for_ship_amount', 0));
        $member_money             = floatval(Yii::$app->request->post('member_money', 0));


        $order                           = new Order();
        $order->source                   = OrderInfo::$SOURCE_MOBILE;
        $order->bestry_uid               = $this->bestry_uid;
        $order->member_address_id        = $member_address_id;
        $order->cart_ids                 = $cart_ids;
        $order->use_coin_for_ship_amount = $use_coin_for_ship_amount;
        $order->member_money             = $member_money;
        $order->sms_confirm_code         = Yii::$app->request->post('smsConfirm', 0);
        $order->validate();
        if ($order->hasErrors()) {
            return ['flag' => false, 'msg' => $order->getErrors()];
        }
        $transaction = Yii::$app->db->beginTransaction();
        OrderDiscount::discount($order, true);
        $order->saveOrder();
        if ($order->hasErrors()) {
            $transaction->rollBack();
            return ['flag' => false, 'msg' => $order->getErrors()];
        }
        $transaction->commit();
        return ['flag'          => true, 'msg' => '',
                'order_sn'      => $order->order_sn,
                'order_info_id' => $order->order_info_id,
                'payed'         => $order->payed,
        ];


    }

    /**
     * 取消订单
     * @param int $order_info_id
     * @return array
     */
    public function actionCancel()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $order_info_id              = intval(Yii::$app->request->get('order_info_id', 0));
        if (empty($order_info_id) && !is_integer($order_info_id)) {
            return ['flag' => false, 'msg' => '订单不正确'];
        }
        if (!$this->isLogin()) {
            return ['flag' => false, 'msg' => '登录后才能退单',];
        }
        $order                = new Order();
        $order->order_info_id = $order_info_id;
        $order->load(['order_info_id' => $order_info_id, 'best_uid' => $this->bestry_uid]);
        if (!$order->cancelOrder()) {
            return ['flag' => false, 'msg' => '操作失败', 'errCode' => $order->getErrors()];
        }
        return ['flag' => true, 'msg' => ''];

    }

    /**
     * 确认支付页面
     * @return string
     */
    public function actionSuccess()
    {
        $order_info_id = Yii::$app->request->get('order_info_id', 0);
        if (empty($order_info_id)) {
            throw new NotFoundHttpException;
        }

        $order = OrderInfo::find()->byPrimary($order_info_id);
        if (empty($order) || (is_object($order) && $order->status >= OrderInfo::$PAY_STATUS_CANCEL)) {
            throw new NotFoundHttpException;
        }
        if (is_object($order) && $order->status >= OrderInfo::$PAY_STATUS_SUCCESS) {
            return $this->redirect(Yii::$app->urlManager->createUrl(['order-details/listwap']));
        }
        return $this->render('@wap/views/cart/success', [
            'order'     => $order,
            'is_wechat' => $this->is_wechat,
        ]);
    }

    /**
     * 检查订单是否支付成功
     */
    public function actionPayRedirect()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $order_info_id = intval(Yii::$app->request->get('order_info_id', 0));
        if (empty($order_info_id)) {
            return ['flag' => false];
        }
        /** @var OrderInfo $order */
        $order = OrderInfo::find()->byPrimary($order_info_id);
        if (is_object($order) && $order->status == OrderInfo::$PAY_STATUS_SUCCESS) {
            return ['flag' => true];
        }
        return ['flag' => false];
    }

    /**
     * 支付完成页
     */
    public function actionPayed()
    {
        $order_info_id = intval(Yii::$app->request->get('order_info_id', 0));
        if (empty($order_info_id)) {
            throw new NotFoundHttpException;
        }
        /** @var OrderInfo $order */
        $order = OrderInfo::find()->byPrimary($order_info_id);
        if (is_object($order) && $order->status == OrderInfo::$PAY_STATUS_SUCCESS) {
            return $this->render('@wap/views/cart/payed', [
                'order' => $order,
            ]);
        }

        return $this->redirect(['order-details/deatilwap', 'order_info_id' => $order_info_id]);

    }


    /**
     * 支付结算验证
     */
    public function actionCartValidate()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $cart_ids                   = $this->cartIdsProc(Yii::$app->request->post('cart_ids', ''));

        $order                           = new Order();
        $order->bestry_uid               = $this->bestry_uid;
        $order->cart_ids                 = $cart_ids;
        $order->use_coin_for_ship_amount = 0;

        $order->validateCustom();

        OrderDiscount::discount($order);
        $order->format();
        $gdms = $order->getDiscountMsg();
        $gdm  = array_filter(
            $gdms, function ($item) {
            /** @var \common\models\OrderDiscount $item */
            if ($item->type == \services\models\discount\FullCut::shortClassName()) {
                return true;
            }
            return false;
        });
        if (!empty($gdm)) {
            $gdm     = array_pop($gdm);
            $fullcut = $gdm->describe;
        } else {
            $fc            = new FullCut();
            $discount_data = $fc->getDataFromRedis();
            if (empty($discount_data)) {
                $fullcut = '';
            } else {
                $fullcut = $discount_data['desc'];
            }

        }
        return ['flag'                 => $order->hasErrors() ? false : true, 'msg' => $order->getErrors(),
                'try_coin'             => $order->try_coin,
                'ship_amount_try_coin' => $order->ship_amount_try_coin,
                'order_amount'         => $order->order_amount,
                'ship_amount'          => $order->ship_amount,
                'ship_amount_discount' => $order->ship_amount_discount,
                'fullcut'              => $fullcut,
                'reduce_amount'        => $order->reduce_amount,
        ];


    }

    /**
     * 订单商品列表页
     */
    public function actionOrderGoods()
    {

        $cart_ids = $this->cartIdsProc(Yii::$app->request->get('cart_ids', ''));
        #var_dump(Yii::$app->request->get('cart_ids', ''));die;

        $cart = Cart::find()
                    ->where(['bestry_uid' => $this->bestry_uid])
                    ->andFilterWhere(['in', 'cart_id', $cart_ids])
                    ->all();
        $data = [];
        #var_dump($cart_ids);
        foreach ($cart as $key => $item) {
            #echo $item->cart_id,"<br>";

            //获取商品详情
            $goods_info = GoodsDetail::findByGoodsId($item->goods_id);
            if (!$goods_info) continue;

            //获取产品规格描述
            $Product_detail_info = ProductDetail::findByProductId($item->product_id);

            //  取产品信息
            $prodcut_info = Product::findByProductId($item->product_id, true, false);
            if (!$prodcut_info) continue;

            $goodPic = Goods::findByGoodsIdFromRedis($item->goods_id, ['pic']);

            if (!in_array(strval($item->cart_id), $cart_ids)) continue;
            //组织data
            $data[$key]['cart_id']    = $item->cart_id;
            $data[$key]['pic']        = Yii::$app->params['goods_image_url'] . str_replace('./upload', 'upload', $goodPic['pic']);
            $data[$key]['goods_name'] = $goods_info['goods_name'];
            $data[$key]['number']     = $item->number;
            $data[$key]['product_id'] = $item->product_id;
            $data[$key]['goods_id']   = $item->goods_id;
            $data[$key]['type_name']  = $prodcut_info['type'] == Product::$_TYPE_TRY ? '试用' : '购买';
            $data[$key]['price_type'] = $prodcut_info['price_type'];
            $data[$key]['price']      = $prodcut_info['price_type'] == Product::$_PRICE_TYPE_RMB ? $prodcut_info['sale_price'] : $prodcut_info['try_price'];

            //取规格信息
            $spec_arr   = [];
            $temp_guige = explode(',', $Product_detail_info['spec_desc']);

            if (!empty($temp_guige[0])) {
                foreach ($temp_guige as $k => $val) {
                    $arr                   = explode(':', $val);
                    $spec_arr[$k]['name']  = $arr[0];
                    $spec_arr[$k]['value'] = $arr[1];
                }
            }

            $data[$key]['spec_desc'] = $spec_arr;

            if ($prodcut_info['price_type'] == Product::$_PRICE_TYPE_RMB) {
                $data[$key]['totoal_price'] = static::formatDecimal($data[$key]['price'] * $item->number);
            } else {
                $data[$key]['totoal_price'] = $data[$key]['price'] * $item->number;
            }
        }

        return $this->render('@wap/views/cart/order-goods', [
            'cart' => $data,
        ]);
    }

    /**
     * 跳转支付宝支付，需要内嵌框架
     */
    public function actionAlipayJump()
    {

        $order_info_id = (int)Yii::$app->request->get('order_info_id', 0);
        if ($order_info_id < 1) {
            throw new Exception('订单ID错误.');
        }
        $hash_value = Payment::getPaymentHash($order_info_id);
        $pay_method = (int)Yii::$app->request->get('pay_method', 1);
        return $this->render('@wap/views/cart/alipay-jump', [
            'order_info_id' => $order_info_id,
            'hash_value'    => $hash_value,
            'pay_method'    => $pay_method,
        ]);
    }
}